package com.pro01.backend.controller;

import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.PointService;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/admin/points")
public class AdminPointController {

    @Autowired
    private PointService pointService;

    /**
     * 管理员分页查看所有用户积分
     */
    @GetMapping
    public Result<PageResult<Map<String, Object>>> getAllUserPoints(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        String role = TokenUtil.getRole(request);
        if (!"ADMIN".equals(role)) {
            return Result.error("无权限，只有管理员可以查看积分");
        }

        try {
            PageResult<Map<String, Object>> result = pointService.getAllUserPoints(pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 管理员奖励/扣除积分
     */
    @PostMapping("/adjust")
    public Result<Void> adjustUserPoints(@RequestBody Map<String, Object> body,
                                         HttpServletRequest request) {
        try {
            String role = TokenUtil.getRole(request);
            if (!"ADMIN".equals(role)) {
                return Result.error("无权限，只有管理员可以操作");
            }

            Long userId = ((Number) body.get("userId")).longValue();
            int points = ((Number) body.get("points")).intValue();
            String changeType = (String) body.get("changeType");
            String description = (String) body.get("description");

            pointService.adjustUserPoints(userId, points, changeType, description);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败：" + e.getMessage());
        }
    }

}
